package com.zg.callback;

import io.netty.handler.codec.mqtt.*;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Set;

/**
 * 处理成功与失败的报文
 */
@Slf4j
public class SuccessOrFailAck {

    //连接成功响应头
    public MqttConnAckMessage connOkAck(MqttConnectVariableHeader mqttConnectVariableHeader,MqttFixedHeader mqttFixedHeader){
        //构建返回报文，可变报头
        MqttConnAckVariableHeader mqttConnAckVariableHeader = new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_ACCEPTED, mqttConnectVariableHeader.isCleanSession());
        //	构建返回报文， 固定报头
        MqttFixedHeader mqttFixedHeaderBack = new MqttFixedHeader(MqttMessageType.CONNACK,mqttFixedHeader.isDup(), MqttQoS.AT_MOST_ONCE, mqttFixedHeader.isRetain(), 0x02);
        //	构建CONNACK消息体
        MqttConnAckMessage connAck = new MqttConnAckMessage(mqttFixedHeaderBack, mqttConnAckVariableHeader);
        log.info("back--"+connAck.toString());
        return connAck;
    }

    //连接失败响应头
    public MqttConnAckMessage connFailAck(MqttConnectVariableHeader mqttConnectVariableHeader,MqttFixedHeader mqttFixedHeader,MqttConnectReturnCode returnCode){
        //构建返回报文，可变报头
        MqttConnAckVariableHeader mqttConnAckVariableHeader = new MqttConnAckVariableHeader(returnCode, mqttConnectVariableHeader.isCleanSession());
        //	构建返回报文， 固定报头
        MqttFixedHeader mqttFixedHeaderBack = new MqttFixedHeader(MqttMessageType.CONNACK,mqttFixedHeader.isDup(), MqttQoS.AT_MOST_ONCE, mqttFixedHeader.isRetain(), 0x02);
        //	构建CONNACK消息体
        MqttConnAckMessage connAck = new MqttConnAckMessage(mqttFixedHeaderBack, mqttConnAckVariableHeader);
        log.info("back--"+connAck.toString());
        return connAck;
    }


    //订阅ack
    public MqttSubAckMessage subAck(List<Integer> grantedQoSLevels, Set<String> topics,MqttMessageIdVariableHeader variableHeaderBack){
        //	构建返回报文	有效负载  128代表订阅失败
        MqttSubAckPayload payloadBack = new MqttSubAckPayload(grantedQoSLevels);
        //	构建返回报文	固定报头
        MqttFixedHeader mqttFixedHeaderBack = new MqttFixedHeader(MqttMessageType.SUBACK, false, MqttQoS.AT_MOST_ONCE, false, 2+topics.size());
        //	构建返回报文	订阅确认
        MqttSubAckMessage subAck = new MqttSubAckMessage(mqttFixedHeaderBack,variableHeaderBack, payloadBack);
        return subAck;
    }


}
